import Phaser from 'https://gitee.com/kiraking/ghl/raw/master/src/lib/phaser.js'

export default class Game extends Phaser.Scene {

    start

	end

	score

	score_text

	calculate_text

	calculate_text_hide

	button_sound
	blast_sound
	hit_sound
	jump_sound
	theme

	char_data

	ground

	girl

	hurt

	sky

	mountain
	grassland4
	grassland3
	grassland2
	grassland1
	tree1
	tree2

	brush

	stones

	gate

	enemies

	blasts

	tip

	go

	attack_zone

	tap_zone

	touching


	constructor() {
		super('game')
	}

	init(data){


		this.char_data = {
			address: '',
			girl_h: 0,
			girl_jump_h: 0,
			enemy_w: 0,
			enemy_h: 0,
			enemy_frame :0
		}


		switch (data.status) {
			case 1:
				this.char_data.address = 'https://gitee.com/kiraking/ghl/raw/master/assets/strawberry';
				this.char_data.girl_h = 112;
				this.char_data.girl_jump_h = 106;
				this.char_data.enemy_w = 50;
				this.char_data.enemy_h = 70;
				this.char_data.enemy_frame = 5;
				break;
			case 2:
				this.char_data.address = 'https://gitee.com/kiraking/ghl/raw/master/assets/kiwi';
				this.char_data.girl_h = 106;
				this.char_data.girl_jump_h = 102;
				this.char_data.enemy_w = 50;
				this.char_data.enemy_h = 66;
				this.char_data.enemy_frame = 4;
				break;
			case 4:
				this.char_data.address = 'https://gitee.com/kiraking/ghl/raw/master/assets/peach';
				this.char_data.girl_h = 116;
				this.char_data.girl_jump_h = 106;
				this.char_data.enemy_w = 72;
				this.char_data.enemy_h = 66;
				this.char_data.enemy_frame = 6;
				break;
			case 8:
				this.char_data.address = 'https://gitee.com/kiraking/ghl/raw/master/assets/tea';
				this.char_data.girl_h = 118;
				this.char_data.girl_jump_h = 110;
				this.char_data.enemy_w = 71;
				this.char_data.enemy_h = 69;
				this.char_data.enemy_frame = 5;
				break;
			}

			this.start = false;
			this.end = false;
			this.score = 0;
			this.calculate_text_hide = 0;
			this.touching = 0;
	}

	preload() {

		this.load.audio('button_sound', 'https://gitee.com/kiraking/ghl/raw/master/assets/sfx/button_sound.mp3')
		this.load.audio('blast_sound', 'https://gitee.com/kiraking/ghl/raw/master/assets/sfx/blast_sound.mp3')
		this.load.audio('hit_sound', 'https://gitee.com/kiraking/ghl/raw/master/assets/sfx/hit_sound.mp3')
		this.load.audio('jump_sound', 'https://gitee.com/kiraking/ghl/raw/master/assets/sfx/jump_sound.mp3')
		this.load.audio('theme', 'https://gitee.com/kiraking/ghl/raw/master/assets/sfx/theme.mp3')

		this.load.image('ground', this.char_data.address + '/ground.png')
		this.load.image('sky', this.char_data.address + '/sky.png')
		this.load.image('mountain', this.char_data.address + '/mountain.png')
		this.load.image('grassland4', this.char_data.address + '/grassland4.png')
		this.load.image('grassland3', this.char_data.address + '/grassland3.png')
		this.load.image('grassland2', this.char_data.address + '/grassland2.png')
		this.load.image('grassland1', this.char_data.address + '/grassland1.png')
		this.load.image('tree1', this.char_data.address + '/tree1.png')
		this.load.image('tree2', this.char_data.address + '/tree2.png')
		this.load.image('brush1', this.char_data.address + '/brush1.png')
		this.load.image('brush2', this.char_data.address + '/brush2.png')
		this.load.image('stone1', 'https://gitee.com/kiraking/ghl/raw/master/assets/stone1.png')
		this.load.image('stone2', 'https://gitee.com/kiraking/ghl/raw/master/assets/stone2.png')
		this.load.image('gate', this.char_data.address +'/gate.png')
		this.load.image('tip', this.char_data.address + '/tip.png')
		this.load.image('go', this.char_data.address + '/go.png')


		this.load.spritesheet('girl', this.char_data.address + '/girl.png', {
			frameWidth: 71,
			frameHeight: this.char_data.girl_h
		})

		this.load.spritesheet('jump', this.char_data.address + '/jump.png', {
			frameWidth: 74,
			frameHeight: this.char_data.girl_jump_h
		})

		this.load.spritesheet('enemy1', this.char_data.address + '/enemy1.png', {
			frameWidth: this.char_data.enemy_w,
			frameHeight: this.char_data.enemy_h
		})

		this.load.spritesheet('enemy2', this.char_data.address + '/enemy2.png', {
			frameWidth: this.char_data.enemy_w,
			frameHeight: this.char_data.enemy_h
		})

		this.load.spritesheet('blast', this.char_data.address + '/blast.png', {
			frameWidth: 334,
			frameHeight: 396
		})

		this.hurt = [0];


		
	}

	create() {

		this.respawnTime = 0;
		this.gameSpeed = 10;
		const { height, width } = this.game.config;

		this.button_sound= this.sound.add('button_sound', { volume: 0.2 });
		this.blast_sound = this.sound.add('blast_sound', { volume: 0.2 });
		this.hit_sound = this.sound.add('hit_sound', { volume: 0.2 });
		this.jump_sound = this.sound.add('jump_sound', { volume: 0.2 });
		this.theme = this.sound.add('theme', { volume: 0.2 });

		this.hurt[0] = 0;

		this.sky = this.add.image(0, height + 200, 'sky').setOrigin(0, 1).setScale(2);

		this.tree2 = this.add.tileSprite(0, height - 100, 652, 425, 'tree2')
			.setOrigin(0, 1)
			.setScale(1.6);

		this.mountain = this.add.tileSprite(0, 880, 652, 425, 'mountain')
			.setOrigin(0, 1)
			.setScale(1.6);
		this.tree1 = this.add.tileSprite(0, height, 652, 425, 'tree1')
			.setOrigin(0, 1)
			.setScale(1.6);
		this.grassland4 = this.add.tileSprite(0, 840, 802, 425, 'grassland4')
			.setOrigin(0, 1)
			.setScale(1.3);
		this.grassland3 = this.add.tileSprite(0, 800, 902, 425, 'grassland3')
			.setOrigin(0, 1)
			.setScale(1.15);
		this.grassland2 = this.add.tileSprite(0, 880, 902, 425, 'grassland2')
			.setOrigin(0, 1)
			.setScale(1.15);
		this.grassland1 = this.add.tileSprite(0, 950, 952, 425, 'grassland1')
			.setOrigin(0, 1)
			.setScale(1.15);

		this.brush = this.add.group();
		this.stones = this.add.group();

		this.ground = this.add.tileSprite(0, height, width, 43, 'ground').setOrigin(0, 1);
		this.physics.add.existing(this.ground);
		this.ground.body.immovable = true;

		this.score_text = this.add
		.text(50, 50, '00000', {fill: '#FFFFFF', fontSize:'36px', fontFamily:'Pixeled',
		shadow:{offsetX: 5, offsetY: 5, blur: 0}})
		.setOrigin(0, 0);
		this.score_text.visible = false;
		this.calculate_text = this.add
		.text(230, 50, '-100', {fill: '#FBFB99', fontSize:'36px', fontFamily:'Pixeled',
		shadow:{offsetX: 5, offsetY: 5, blur: 0}})
		.setOrigin(0, 0);
		this.calculate_text.visible = false;
		
		this.girl = this.physics.add.sprite(200, height - 43, 'girl')
			.setOrigin(0.5, 1)
			.setCollideWorldBounds(true)
			.setGravityY(5000)
		this.girl.depth = 50;

		this.enemies = this.physics.add.group();
		this.blasts = this.add.group();

		this.gate = this.physics.add.sprite(width, height - 43, 'gate').setOrigin(0, 1);

		this.attack_zone = this.add.zone(200, height - 170 - 43).setSize(20, 20);
		this.physics.world.enable(this.attack_zone);
		this.attack_zone.body.immovable = true;

		this.tap_zone = this.add.zone(width /2, height/2, width, height).setInteractive();

		this.tip = this.add.image(width /2, height/2, 'tip');
		this.go = this.add.image(width /2, height/2 + 100, 'go').setInteractive();
		this.go.on('pointerdown', () => { 
			this.button_sound.play();
			this.go.visible = false; 
			this.tip.visible = false 
			this.score_text.visible = true;
			this.start = true;
			this.theme.play();
		})

		this.handleScore()
		this.initAnims();
		this.initColliders();
		this.tintTween();

		this.tap_zone.on('pointerdown', () => {
			if (this.start && this.girl.body.onFloor()){
				this.girl.play('girl_jump_up', true);
				this.girl.setVelocityY(-1600);
				this.touching = 2;
				this.jump_sound.play();
			}
		})
	}

	initAnims() {
		this.anims.create({
			key: 'girl_run',
			frames: this.anims.generateFrameNumbers('girl', { start: 0, end: 7 }),
			frameRate: 12,
			repeat: -1
		})

		this.anims.create({
			key: 'girl_jump_up',
			frames: this.anims.generateFrameNumbers('jump', { start: 0, end: 1 }),
			frameRate: 12,
			repeat: 0
		})

		this.anims.create({
			key: 'girl_jump_down',
			frames: this.anims.generateFrameNumbers('jump', { start: 2, end: 2 }),
			frameRate: 12,
			repeat: 0
		})

		this.anims.create({
			key: 'girl_jump_touch',
			frames: this.anims.generateFrameNumbers('jump', { start: 3, end: 3 }),
			frameRate: 12,
			repeat: 0
		})

		this.anims.create({
			key: 'enemy1',
			frames: this.anims.generateFrameNumbers('enemy1', { start: 0, end: this.char_data.enemy_frame - 1}),
			frameRate: 4,
			repeat: -1
		})

		this.anims.create({
			key: 'enemy2',
			frames: this.anims.generateFrameNumbers('enemy2', { start: 0, end: this.char_data.enemy_frame - 1}),
			frameRate: 4,
			repeat: -1
		})

		this.anims.create({
			key: 'blast',
			frames: this.anims.generateFrameNumbers('blast', { start: 0, end: 7 }),
			frameRate: 12,
			repeat: 0
		})
	}

	initColliders() {

		const { height, width } = this.game.config;

		this.physics.add.collider(this.girl, this.ground);

		this.physics.add.overlap(this.girl, this.gate, () => {
			this.theme.stop();
			this.scene.start('ending', {score: this.score, address: this.char_data.address}) 
		});

		this.physics.add.overlap(this.girl, this.attack_zone);

		this.physics.add.overlap(this.girl, this.enemies, (girl, enemy) => {
			if (this.attack_zone.body.touching.none || girl.body.facing != Phaser.Physics.Arcade.FACING_DOWN) {
				if (this.hurt[0] > 0) { return; }
				
				this.hit_sound.play();

				this.hurt[0] += 40;
				if (this.score < 100) { this.score = 0;}
				else{this.score -= 100; } 
				this.calculate_text.setColor('#FB9999').setText('-100');
				
			}
			else {
				const x = enemy.x;
				enemy.destroy();
				var blast = this.blasts.create(x, height, 'blast')
					.setOrigin(0.5, 1);
				blast.play('blast').setScale(0.6);
				
				this.blast_sound.play();

				this.score += 100;
				this.calculate_text.setColor('#FBFB99').setText('+100');
			}

			this.tweens.add({
				targets: this.calculate_text,
				duration: 120,
				repeat: 3,
				alpha: 0,
				yoyo: true,
				getStart: () => {this.calculate_text.visible = true;},
				getEnd: () => {
					console.log(this.calculate_text_hide);
					if (this.calculate_text_hide >= 3){ 
						this.calculate_text.visible = false;
						this.calculate_text_hide = 0;
					}
					else { this.calculate_text_hide++ }
				}
			  })

		});


	}

	handleScore() {
		this.time.addEvent({
		  delay: 1000 / 10,
		  loop: true,
		  callbackScope: this,
		  callback: () => {
			if (!this.start || this.end) { return; }
	
			this.score++;
			this.gameSpeed += 0.01
	
			const score = Array.from(String(this.score), Number);
			for (let i = 0; i < 5 - String(this.score).length; i++) {
			  score.unshift(0);
			}
	
			this.score_text.setText(score.join(''));
		  }
		})
	}

	placeRoadside(){
		const { height, width } = this.game.config;

		const sideroadNum = Math.random();
		const distance = Phaser.Math.Between(50, 500);

		var single_brush = '';
		var stone = '';


		if (sideroadNum <= 0.25){
			single_brush = 'brush1';
			stone = 'stone1';
		}
		else if (sideroadNum > 0.25 &&  sideroadNum <= 0.5){
			single_brush = 'brush1';
			stone = 'stone2';
		}
		else if (sideroadNum > 0.5 &&  sideroadNum <= 0.75){
			single_brush = 'brush2';
			stone = 'stone1';
		}
		else{
			single_brush = 'brush2';
			stone = 'stone2';
		}

		this.brush.create(width + distance, height - 40, single_brush)
			.setOrigin(0.5, 1)
		this.stones.create(width + distance + Phaser.Math.Between(-3, 3) * 15, height - 43, stone)
			.setOrigin(0.5, 1)

	}

	placeEnemy() {
		const { height, width } = this.game.config;

		const enemyNum = Math.random();
		const distance = Phaser.Math.Between(500, 900);


		var enemy;

		if (enemyNum >= 0.5) {


			enemy = this.enemies.create(width + distance, height - 43, 'enemy1')
				.setOrigin(0.5, 1);
			enemy.depth = 100;
			enemy.play('enemy1');
		}
		else {
			enemy = this.enemies.create(width + distance, height - 43, 'enemy2')
				.setOrigin(0.5, 1);
			enemy.depth = 100;
			enemy.play('enemy2');
		}

	}

	tintTween() {
		var girl = this.girl;
		var hurt = this.hurt;
		this.tweens.addCounter({
			from: 255,
			to: 100,
			duration: 200,
			repeat: -1,
			onUpdate: function (tween) {

				if (hurt[0] == 0) 
				{
					girl.clearTint();
					return;
				}

				const value = Math.floor(tween.getValue());


				girl.setTint(Phaser.Display.Color.GetColor(255, value, value));

				hurt[0]--;
			}
		});
	}

	update(time, delta) {

		if (!this.start) { return; }

		this.ground.tilePositionX += this.gameSpeed;
		this.tree2.tilePositionX += this.gameSpeed * 0.1;
		this.tree1.tilePositionX += this.gameSpeed * 0.15;
		this.mountain.tilePositionX += this.gameSpeed * 0.2;
		this.grassland4.tilePositionX += this.gameSpeed * 0.3;
		this.grassland3.tilePositionX += this.gameSpeed * 0.4;
		this.grassland2.tilePositionX += this.gameSpeed * 0.5;
		this.grassland1.tilePositionX += this.gameSpeed * 0.6;
		Phaser.Actions.IncX(this.brush.getChildren(), -this.gameSpeed);
		Phaser.Actions.IncX(this.stones.getChildren(), -this.gameSpeed);
		Phaser.Actions.IncX(this.enemies.getChildren(), -this.gameSpeed);
		Phaser.Actions.IncX(this.blasts.getChildren(), -this.gameSpeed);

		
		if(this.end) { this.gate.x -= this.gameSpeed; }

		this.respawnTime += delta;

		if (this.enemies.getLength() + this.blasts.getLength() >= 15){
			if (this.respawnTime >= 20000 / this.gameSpeed){ this.end = true; }
		}
		else if (this.respawnTime >= 12000 / this.gameSpeed) {
			this.placeEnemy();
			this.respawnTime = 0;
		}
		else if (this.respawnTime / 3 - Math.floor(this.respawnTime / 3) < 0.01){
			this.placeRoadside();
		}

		if (this.girl.body.onFloor()) {
			if (this.touching <= 0)
			{ this.girl.play('girl_run', true); }
			else
			{ 
				this.girl.play('girl_jump_touch', true); 
				this.touching--;
		    }
		}
		else if (this.girl.body.deltaY() > 0 && this.girl.body.y < 420){
			this.girl.play('girl_jump_down', true);
		}
		




	}





}